package web.video;

import bean.Union;
import bean.Video;
import com.alibaba.fastjson.JSON;
import entity.VideoEntity;
import util.FANREN;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@WebServlet(name = "VideoList", urlPatterns = "/dao/videoList")
public class VideoList extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        //当前页数（一页4条）
        String jsonString = FANREN.getJson(request);
        Union union = JSON.parseObject(jsonString,Union.class);
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        Query query;
        if(union.getSearch().equals("")){
            query = em.createQuery("select v from VideoEntity v");
        } else {
            query = em.createQuery("select v from VideoEntity v where v.name like '%" + union.getSearch() + "%'");
        }
        List<VideoEntity> list = query.getResultList();

        int totalPage = list.size();

        int pos = (union.getCurrentPage() - 1) * 4;

        List<Video> videoList = new ArrayList<>();
        for (int i=0,j=pos; i<4&&j<list.size(); i++,j++) {
            Video video = new Video();
            video.setVid(String.valueOf(list.get(j).getVid()));
            video.setName(list.get(j).getName());
            video.setAuthor(""+list.get(j).getUid().getName());
            video.setIntroduce(list.get(j).getIntroduce());
            video.setTime(list.get(j).getTime());
            video.setType(""+list.get(j).getTid().getName());
            video.setViews(list.get(j).getViews());
            video.setAv(list.get(j).getAv());
            video.setImgUrl(list.get(j).getImgUrl().equals("")?"http://localhost:8080/img/default.jpg":list.get(j).getImgUrl());
            videoList.add(video);
        }
        String returnString = "{\"tableData\":" + JSON.toJSONString(videoList) +",\"totalPage\":" + totalPage + "}";
        response.getWriter().write(URLEncoder.encode(returnString,StandardCharsets.UTF_8));
    }
}
